﻿namespace Digitalmes.Application.Sys.Roles.Commands;

/// <summary>
/// 更新角色命令。
/// </summary>

public record UpdateRoleCommand(SysRoleDto Role) : IRequest<IResult<bool>>;

internal sealed class UpdateRoleCommandHandler(IRepository<SysRole> repo) : IRequestHandler<UpdateRoleCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
    {
        // 检查账号名是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Role.Code && m.Id != request.Role.Id, cancellationToken))
        {
            return Result.Failure("角色编号已存在");
        }

        var role = request.Role.Adapt<SysRole>();
        var ok = await repo.UpdateAsync(role, m => new
        {
            m.Name,
            m.Order,
            m.Remark,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
